<template>
  <div class="screen-fit" :style="styleInfo">
    <slot></slot>
  </div>
</template>
<script setup lang="ts">
import {ref, onMounted, onBeforeUnmount} from 'vue'
import {IStyle} from './types'

// Props
const props = defineProps({
  width: {
    type: String,
    default: '1920'
  },
  height: {
    type: String,
    default: '1080'
  }
})

// Style Info
const styleInfo = ref<IStyle>({
  width: props.width + 'px',
  height: props.height + 'px',
  transform: 'scale(1) translate(-50%, -50%)'
})

// 获取缩放比例
const getScale = () => {
  const w = window.innerWidth / +props.width
  const h = window.innerHeight / +props.height
  return [w, h]
}

// 设置缩放样式
const setScale = () => {
  const [w, h] = getScale()
  styleInfo.value.transform = `scale(${w}, ${h}) translate(-50%, -50%)`
}

// 初始化 & Resize 监听
onMounted(() => {
  setScale()
  window.addEventListener('resize', setScale)
})

// 建议：在组件卸载时移除监听器
onBeforeUnmount(() => {
  window.removeEventListener('resize', setScale)
})
</script>

<style lang="scss" scoped>
.screen-fit {
  position: absolute;
  top: calc(50%);
  left: 50%;
  transform-origin: 0 0;
  transition: 0.3s;
}
</style>
